package com.mask.mk.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mask.mk.pojo.MUser;
import com.mask.mk.mapper.MUserMapper;
import com.mask.mk.service.MUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mask.mk.util.JsonResult;
import com.mask.mk.vo.login.LoginRequest;
import com.mask.mk.vo.login.RegisterRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author joey
 * @since 2023-04-25
 */
@Service
public class MUserServiceImpl implements MUserService {

    @Autowired
    private MUserMapper mUserMapper;
    @Override
    public JsonResult login(LoginRequest loginInfo) {

        JsonResult result=null;
//        JsonResult result = new JsonResult();
        MUser selectOne = mUserMapper.selectOne(Wrappers.<MUser>lambdaQuery()
                .and(wrapper -> wrapper
                        .eq(MUser::getPhone, loginInfo.getUserAccount())
                        .eq(MUser::getPassword, loginInfo.getPassword())));
        if(selectOne != null){
            System.out.println("登录用户=> "+selectOne);
            result =JsonResult.success(selectOne);
        }else{
            result =JsonResult.fail("账号或密码错误");
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult register(RegisterRequest registerRequest) {
        MUser mUser = new MUser();
        JsonResult result=null;
        MUser selectOne = mUserMapper.selectOne(Wrappers.<MUser>lambdaQuery()
                .and(wrapper -> wrapper
                        .eq(MUser::getPhone, registerRequest.getUserAccount())));
        if(registerRequest!=null){
            if(selectOne==null){
                mUser.setUserName(registerRequest.getUserName()).setPhone(registerRequest.getUserAccount())
                        .setUserLevel(1)
                        .setPassword(registerRequest.getUserAccount().substring(5,11)) //密码截取手机号后6位
                        .setIdentify(1);
                mUserMapper.insert(mUser);
                result = JsonResult.success(mUser);
            }else{
                System.out.println("手机号重复");
                result = JsonResult.fail("手机号重复");
            }
        }

        return result;
    }
}
